package com.study.zookeeper.case2;

import org.apache.zookeeper.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

public class DistributeServer {
    private String connectString = "hadoop102:2181,hadoop103:2181,hadoop104:2181";
    private int sessionTimeout = 2000;
    private ZooKeeper zooKeeper;

    public static void main(String[] args) {
        DistributeServer distributeServer = new DistributeServer();
        //获取连接
        distributeServer.getConnection();
        //注册服务到zookeeper
        distributeServer.regist(args[0]);
        //业务逻辑
        distributeServer.business();
    }

    private void business() {
        try {
            TimeUnit.SECONDS.sleep(Long.MAX_VALUE);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void regist(String hostname) {
        try {
            String s = zooKeeper.create("/servers/"+hostname, hostname.getBytes(StandardCharsets.UTF_8), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
            System.out.println(hostname + "  上线了");
        } catch (KeeperException | InterruptedException e) {
            System.out.println(hostname+"节点注册失败!!!");
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取与zookeeper的连接
     *
     * @return
     */
    private void getConnection() {
        try {
            zooKeeper = new ZooKeeper(connectString, sessionTimeout,(watchedEvent) -> {

            });
        } catch (IOException e) {
            System.out.println("连接zookeeper失败！！！");
            throw new RuntimeException(e);
        }
    }
}
